package com.boarsoft.dubbo.loadbalance;

import java.util.List;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;

/**
 * 指定ip、port 的dubbo负载均衡策略
 * 
 * @author wshh-wudufeng
 *
 */
@Deprecated
public class HostPortLoadBalance extends RandomLoadBalance {
	private static ThreadLocal<Object[]> hostAndPort = new ThreadLocal<Object[]>();

	public HostPortLoadBalance(){
		System.out.println("init HostPortLoadBalance:");
	}
	
	@Override
	protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
		Object[] hostPort = hostAndPort.get();
		System.out.println("HostPortLoadBalance.doSelect:hostAndPort:" + hostAndPort);
		if (hostPort != null) {
			try {
				for (Invoker<T> invoker : invokers) {
					// 判断invoker是否指定的host和端口
					if (invoker.getUrl().getHost().equals(hostPort[0])
							&& (invoker.getUrl().getPort() == (Integer) hostPort[1])) {

						return invoker;
					}
				}

				// 无对应的提供者
				throw new RuntimeException(String.format("service not found at %s:%s", //
						(String) hostPort[0], String.valueOf(hostPort[1])));

			} finally {
				hostAndPort.set(null);
			}
		}

		return super.doSelect(invokers, url, invocation);

	}

	/**
	 * 
	 * @param host
	 * @param port
	 */
	public static void setHostAndPort(String host, Integer port) {
		hostAndPort.set(new Object[] { host, port });
	}
}
